<?php

namespace Narti\BouncerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Component\HttpFoundation\Response;

use Narti\BouncerBundle\Entity\Landline;
use Narti\BouncerBundle\Form\LandlineType;
use Narti\BouncerBundle\Repository\LandlineRepository;



/**
 * Landline controller.
 *
 * @Route("/bouncing/landline")
 */
class LandlineController extends Controller
{
    
    private $ename = 'NartiBouncerBundle:Landline';
      
    /**
     * Lists all Landline entities.
     *
     * @Route("/", name="landline")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
 
        $request = $this->get('request');
        if($request->isXmlHttpRequest()){
             
             $page = $request->request->get('page');
             $limit = $request->request->get('rows');
             $sidx = $request->request->get('sidx');
             $sord = $request->request->get('sord'); // get the direction
           
             if (!$page) $page = 1;
  	     if (!$limit) $limit = 10;
             
             $count = (int) $em->getRepository($this->ename)
                      ->countAll();
             
             $total_pages = ( $count > 0) ?  ceil( $count / $limit ) : 0;              
             if ($page > $total_pages) $page=$total_pages;
             
             
             $result = array();
             $result['page'] = $page;
             $result['total'] = $total_pages;
             $result['records'] = $count;
             
             $result['rows'] = array();
             
             $entities = array();
             if($count > 0 ){
                $rowStart = $page * $limit - $limit;
                $entities = $em->getRepository($this->ename)
                            ->findPage($limit, $rowStart, $sidx, $sord );
             }
             
                      
             foreach ($entities as $entity){
                   $result['rows'][] = array(
                   'id' => $entity['id'],
                   'cell' => array($entity['id'] ,
                                   $entity['bounce'], 
                                   $entity['titolo'],
                                   substr($entity['contenuto'], 0, 40) . '...',
                                   $entity['rnd'],
                                   $entity['nome'],
                                   $entity['createdAt'],
                                  
                           )
                   );
            }
                       
           
         // $cazzo = json_encode($result);
            $response = new Response(json_encode($result));
            $response->headers->set('Content-Type', 'application/json');
            return $response;

       }
       
       return $this->render('NartiBouncerBundle:Landline:index.html.twig');

    }

    /**
     * Displays a form to create a new Landline entity.
     *
     * @Route("/new", name="landline_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Landline();
              
        $request = $this->getRequest();
        return  $this->getData($entity, $request);
        

        return array(
            'entity' => $entity,
            'form'   => $form->createView()
        );
    }

    /**
     * Creates a new Landline entity.
     *
     * @Route("/create", name="landline_create")
     * @Method("post")
     * @Template("NartiBouncerBundle:Landline:new.html.twig")
     */
    public function createAction()
    {
        $entity = new Landline();
        
        $request = $this->getRequest();
        return  $this->postData($entity, $request);
    }

    /**
     * Displays a form to edit an existing Landline entity.
     *
     * @Route("/{id}/edit", name="landline_edit")
     * @Template()
     */
    public function editAction($id)
    {
       $em = $this->getDoctrine()->getEntityManager();
       $entity = $em->getRepository($this->ename)->find($id);

       if (!$entity) {
           throw $this->createNotFoundException('Errore find Landline entity.');
       }
        
        $request = $this->getRequest();
        return  $this->getData($entity, $request);

    }

    /**
     * Edits an existing Landline entity.
     *
     * @Route("/{id}/update", name="landline_update")
     * @Method("post")
     * @Template("NartiBouncerBundle:Landline:edit.html.twig")
     */
    public function updateAction($id)
    {
         $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository($this->ename)->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Errore find Landline entity.');
        }


        $request = $this->getRequest();
        return  $this->postData($entity, $request);
    }
    
     /**
     * Deletes a Landline entity.
     *
     * @Route("/{id}/delete", name="landline_delete")
     * @Method("post")
     */
     public function deleteAction($id){
         
         $em = $this->getDoctrine()->getEntityManager(); 
         $entity = $em->getRepository($this->ename)->find($id);

         if (!$entity) {
             throw $this->createNotFoundException('Errore find Landline entity.');
         }
         
         $em->remove($entity);
         $em->flush();
         
         $request = $this->getRequest();
         
         // ajax
         if($request->isXmlHttpRequest()){
              $data = array(
                  'result' => '200'
              );
              
              $response = new Response(json_encode($data));
              $response->headers->set('Content-Type', 'application/json');
              return $response;
          }
    }
    

      
    private function getData($entity, $request){
      
        $form   = $this->createForm(new LandlineType(), $entity);
        
        if($request->isXmlHttpRequest()){
            return array(
            'entity' => $entity,
            'form'   => $form->createView()
            );
        
        }
    }
    
    private function postData($entity, $request){
        
        $form   = $this->createForm(new LandlineType(), $entity);
        
        $form->bindRequest($request); 
        if ($form->isValid()) {
            
            if($entity->getId() === null){
       //         $entity->setCreatedAt(new \DateTime("now"));
                $entity->setRnd(rand());
            }
            
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($entity);
            $em->flush();
                
        }
        
        if($request->isXmlHttpRequest()){
            return array(
            'entity' => $entity,
            'form'   => $form->createView()
            );
         
        }
        
    }
}
